package openase.audiosearch.client;

import java.io.File;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.FileConfiguration;
import org.apache.commons.configuration.PropertiesConfiguration;

public class ClientProperties {

	private static final String SERVER_HOST = "server.ip";
	private static final String SERVER_PORT = "server.port";
	private static final String MAX_RESULTS = "maxresults";

	private static volatile ClientProperties instance;

	private static ClientProperties getInstance() {
		if (instance == null) {
			synchronized (ClientProperties.class) {
				if (instance == null) {
					instance = new ClientProperties();
				}
			}
		}
		return instance;
	}

	public static String getServerIP() {
		return getInstance().innerGetServerIP();
	}

	public static int getServerPort() {
		return getInstance().innerGetServerPort();
	}

	public static int getMaxResults() {
		return getInstance().innerGetMaxResults();
	}

	private FileConfiguration config;

	private ClientProperties() {
		try {
			config = new PropertiesConfiguration(new File("audiosearch.properties"));
		} catch (ConfigurationException e) {
			throw new RuntimeException();
		}
	}

	private String innerGetServerIP() {
		reloadFile();
		return config.getString(SERVER_HOST, "127.0.0.1");
	}

	private int innerGetServerPort() {
		reloadFile();
		return config.getInt(SERVER_PORT, 17555);
	}

	private int innerGetMaxResults() {
		reloadFile();
		return config.getInt(MAX_RESULTS, 20);
	}

	private void reloadFile() {
		try {
			config.clear();
			config.load();
		} catch (ConfigurationException e) {
			// ignore
		}
	}

}
